const request = require('request');
const async = require('async');
const cheerio = require('cheerio');


function visiteSite(url, cb) {
	request({
		url: url,
		headers: {
			'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
			'Accept-Language': 'zh-CN,zh;q=0.8,zh-HK;q=0.6',
			'Cache-Control': 'no-cache',
			'Connection': 'keep-alive',
			'Host': 'www.weather.com.cn',
			'Pragma': 'no-cache',
			'Referer': 'http://www.weather.com.cn/weather/101200101.shtml',
			'Upgrade-Insecure-Requests': 1,
			'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
		}
	}, function(err, response, body) {
		if (err) return cb(err);
		if (response.statusCode != 200) {
			return cb(new Error(`response code ${response.statusCode}`));
		}
		cb(null, response.body);
	})
}

function parseHtml(html, cb) {
	require('fs').writeFile('index.html',html);
	let $ = cheerio.load(html);
	let dayTem,nightTem;
	$('.today .clearfix p.tem').children('span').each((i,e)=>{
		if(i === 0) {
			dayTem = $(e).text();
		}else {
			nightTem = $(e).text();
		}
	});
	let dayWea,nightWea;
	$('.today .clearfix p.wea').each((i,e)=>{
		if(i === 0) {
			dayWea = $(e).text();
		}else {
			nightWea = $(e).text();
		}
	});
	let live = [];
	$('.livezs>ul>li').each((i,e)=>{
		live.push({
			name: $(e).find('em').text(),
			status: $(e).find('span').text(),
			desc: $(e).find('p').text()
		});
	});
	cb(null, {
		dayTem,
		nightTem,
		dayWea,
		nightWea,
		live
	});
}

let url = 'http://www.weather.com.cn/weather1d/101200101.shtml';
async.waterfall([
	function(cb) {
		visiteSite(url, cb)
	},
	parseHtml
], (err, result) => {
	if (err) {
		console.log(err)
		return
	}
	console.log(result)
})